package com.rc.evcharger.protocol.ylevcharger.action;

import com.rc.evcharger.common.base.yl.BaseYlCommAction;
import com.rc.evcharger.common.code.YlControlCode;
import com.rc.evcharger.common.constant.SocketConstant;
import com.rc.evcharger.model.elec.ElecGun;
import com.rc.evcharger.model.elec.ElecPile;
import com.rc.evcharger.protocol.ylevcharger.service.YlChargeMessageService;
import com.rc.evcharger.service.elec.ElecGunService;
import com.rc.evcharger.service.elec.ElecPileService;
import com.rc.mutievcharger.dto.ylevcharger.terminal.*;
import com.rc.mutievcharger.dto.ylevcharger.terminal.req.*;
import com.rc.mutievcharger.dto.ylevcharger.utils.YlMessageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.List;

/**
 * 本地执行的逻辑（偏通讯）,会返回响应指令
 */
@Component
public class YlCommAction implements BaseYlCommAction<YlTerminalMessage> {
    private static Logger logger = LoggerFactory.getLogger(YlCommAction.class);

    @Autowired
    private ElecPileService elecPileService;

    @Autowired
    private ElecGunService elecGunService;

    @Autowired
    private YlChargeMessageService ylChargeMessageService;

    /**
     * 登录指令
     *
     * @param msg
     * @return
     */
    @Override
    public String login(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        ElecPile elecPile = elecPileService.selectByPrimaryKey(elecGun.getElecPileId());
        if (elecPile == null) {
            return "";
        }
        YlLoginCommondReq loginCommondReq = (YlLoginCommondReq) new YlLoginCommondReq().getResult(msg.getData());
        loginCommondReq.setTerminalId(msg.getTerminalId());

        YlLoginCommondResp loginCommondResp = new YlLoginCommondResp("00");

        //回复桩
        return YlMessageUtil.getResponse(msg, YlControlCode.RESP_LOGIN_69, loginCommondResp);
    }

    @Override
    public String logout(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        ElecPile pile = elecPileService.selectByPrimaryKey(elecGun.getElecPileId());
        if (pile == null) {
            return "";
        }
        if (pile == null) {
            return "";
        }

        //TODO 可能需要事务
        ylChargeMessageService.loginOut(elecGun);
        return "";
    }

    /**
     * 心跳检查
     */
    @Override
    public String hearBeat(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        ElecPile elecPile = elecPileService.selectByPrimaryKey(elecGun.getElecPileId());
        if (elecPile == null) {
            return "";
        }
        //防止有心跳却离线
        int loginStatus = elecPileService.isLoginStatus(elecPile);
        if (loginStatus == SocketConstant.CON0) {
            return "";
        }


        //解析得到请求数据
        YlHearBeatCommondReq result = (YlHearBeatCommondReq) new YlHearBeatCommondReq().getResult(msg.getData());

        YlHearBeatCommondResp hearBeatCommondResp = new YlHearBeatCommondResp(result);

        return YlMessageUtil.getResponse(msg, YlControlCode.RESP_HEARTBEAT_MONITOR, hearBeatCommondResp);
    }

    /**
     * 电价确认
     *
     * @param msg
     * @return
     */
    @Override
    public String priceConfirem(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        ElecPile pile = elecPileService.selectByPrimaryKey(elecGun.getElecPileId());
        if (pile == null) {
            return "";
        }
        //1102指令
        YlPriceConfiremCommandReq result = (YlPriceConfiremCommandReq) new YlPriceConfiremCommandReq().getResult(msg.getData());

        Class<? extends YlPriceConfiremCommandReq> aClass = result.getClass();

        Field[] declaredFields = aClass.getDeclaredFields();
        StringBuilder stringBuilder = new StringBuilder();
        for (Field field : declaredFields) {
            // 如果类型是String
            if (field.getGenericType().toString().equals(
                    "class java.math.BigDecimal")) { // 如果type是类类型，则前面包含"class "，后面跟类名

                //首字母转大写
                byte[] items = field.getName().getBytes();
                items[0] = (byte) ((char) items[0] - 'a' + 'A');

                // 拿到该属性的gettet方法
                Method m = null;
                BigDecimal val = null;//
                try {
                    // 拿到该属性的gettet方法
                    m = result.getClass().getMethod(
                            "get" + new String(items));

                    //调用getter方法获取属性值
                    val = (BigDecimal) m.invoke(result);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
                if (val != null) {
                    stringBuilder.append("BigDecimal type:").append((val.toString().length() == 1 ? "0" + val : val.toString())).append("\n");
                }
            }
        }
        logger.info("电价确认桩编号:{}对应电价为:{}", stringBuilder);
        return "";
    }

    /**
     * 下发电价
     *
     * @param msg
     * @return
     */
    @Override
    public String priceRequest(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        ElecPile pile = elecPileService.selectByPrimaryKey(elecGun.getElecPileId());
        if (pile == null) {
            return "";
        }

        logger.info("桩电价下发成功,对应桩编号:{}", pile.getPileNo());
//        List<ElecStationPrice> list = elecStationPriceService.listByStationId(pile.getElecStationId());
//        ElecStationPrice elecStationPrice = null;
//        if (CollectionUtils.isEmpty(list)) {
//            elecStationPrice = new ElecStationPrice(BigDecimal.ZERO, BigDecimal.ZERO);
//        } else {
//            elecStationPrice = list.get(0);
//        }
//        BigDecimal totalAmount = elecStationPrice.getServicePrice().add(elecStationPrice.getElecPrice());
//
//        //拼接回复报文
//        YlPriceRequestCommondResp priceConfiremCommandResp = new YlPriceRequestCommondResp();
//
//        StringBuffer rateNums = new StringBuffer();
//        for (int i = 0; i < 48; i++) {
//            rateNums.append(SocketConstant.FLATP_NUM).append(SocketConstant.SPLIT); //平谷
//        }
//        //priceConfiremCommandResp.setRateNums(rateNums.toString().trim());
//        priceConfiremCommandResp.setTerminalId(msg.getTerminalId());
        return "";
//        return YlMessageUtil.getResponse(msg, YlControlCode.RESP_PRICE_REQUEST, priceConfiremCommandResp);
    }

    /**
     * 充电中数据
     *
     * @param msg
     * @return
     */
    @Override
    public String chargeDataReport(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        ElecPile pile = elecPileService.selectByPrimaryKey(elecGun.getElecPileId());
        if (pile == null) {
            return "";
        }

        YlChargingCommandReq chargingCommandReq = (YlChargingCommandReq) new YlChargingCommandReq().getResult(msg.getData());

        YlChargingCommandResp chargingCommandResp = new YlChargingCommandResp(chargingCommandReq.getGunNum());
        chargingCommandResp.setTerminalId(msg.getTerminalId());

        //充电实时数据回复
        return YlMessageUtil.getResponse(msg, YlControlCode.RESP_ELEC_STATUS, chargingCommandResp);
        //return "";
    }

    @Override
    public String transactonsReport(YlTerminalMessage msg) {
        ElecGun elecGun = elecGunService.selectGunByGunNo(msg.getTerminalId());
        ElecPile pile = elecPileService.selectByPrimaryKey(elecGun.getElecPileId());
        if (pile == null) {
            return "";
        }

        YlTransactionsCommandReq transactionsCommandReq = (YlTransactionsCommandReq) new YlTransactionsCommandReq().getResult(msg.getData());

        //回复指令
        YlTransactionsCommandResp transactionsCommandResp = new YlTransactionsCommandResp(transactionsCommandReq);

        //交易记录回复
        return YlMessageUtil.getResponse(msg, YlControlCode.ELEC_DATA_BALANCE_RES, transactionsCommandResp);
    }

    @Override
    public String startResp(YlTerminalMessage msg) {
        //不需要回复
        return "";
    }

    @Override
    public String stopResp(YlTerminalMessage msg) {
        //不需要回复
        return "";
    }

    @Override
    public String timing(YlTerminalMessage msg) {
        return "";
    }

    @Override
    public String balanceUpdateResp(YlTerminalMessage msg) {
        return "";
    }

    @Override
    public String warnCode(YlTerminalMessage msg) {
        //不做回复处理
        return "";
    }


    ///**
    // * 充电数据自动上报 获取充电数据并存入redis中
    // */
    //@Override
    //public String chargeReport(ZcTerminalMessage msg) {
    //    return "";
    //}

}
